//
//  MCUpdataModule.m
//  MCPublicModule
//
//  Created by Mirko on 16/8/25.
//  Copyright © 2016年 Mirko. All rights reserved.
//

#import "MCUpdateModule.h"
#import "AFNetworking.h"
#import "MCUpdateInfoModel.h"
#import "MJExtension.h"

static MCUpdateModule *updateModule = nil;

NSString *const kUpdateButtonTitle = @"升级";
NSString *const kCancelButtonTitle = @"取消";
NSString *const kUpdateUSDefautlKey = @"update_module";

@interface MCUpdateModule ()

@property (nonatomic, strong) MCUploadInfoModel *uploadInfo;
@property (nonatomic, strong) VersionCheckCompleteBlock completeBlock;
@property (nonatomic, strong) MCUpdateInfoModel *info;
@property (nonatomic, strong) UIAlertView *alert;


@end

@implementation MCUpdateModule

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

+(void) checkVersion:(MCUploadInfoModel *) info block:(VersionCheckCompleteBlock) block;
{
    MCUpdateModule *module = [MCUpdateModule instance];
    if (module.uploadInfo) {
        DLOG(@"Is checking!");
        block(kNeedUpdateing,nil,nil);
        return;
    }
    module.uploadInfo = info;
    module.completeBlock = block;
    [module startCheckVersion];
}

+(instancetype) instance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        updateModule = [[MCUpdateModule alloc] init];
    });
    return updateModule;
}

-(instancetype) init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:)
                                                     name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}

-(EMCUpdateModuleStatus) status
{
    return _status;
}

-(void) setStatus:(EMCUpdateModuleStatus) status
{
    _status = status;
}

-(void) startCheckVersion
{
    NSString *url = self.uploadInfo.requestUrl;
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperationManager manager] POST:url parameters:[self.uploadInfo parameters] success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSInteger requestCode = [responseObject[@"rs_code"] integerValue];
        if (requestCode != 1000) {
            NSError *err = [NSError errorWithDomain:responseObject[@"rs_msg"] code:requestCode  userInfo:@{@"ErrDesc": @"Request Suss but code is not 1000"}];
            [self checkRequstFailed:err];
        }
        else
        {
            [self checkRequestsuccess:responseObject];
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self checkRequstFailed:error];
        DLOG(@"%@", error);
    }];
    [operation resume];
}

-(void) checkRequstFailed:(NSError *) error
{
    self.completeBlock(kNetworkErr, nil, error);
}

-(void) checkRequestsuccess:(id) responseObject
{
    NSDictionary *updateInfo = responseObject[@"details"];
    self.info = [MCUpdateInfoModel mj_objectWithKeyValues:updateInfo];
    DLOG(@"%@", self.info);
    if (!self.alert) {
        self.alert = [[UIAlertView alloc] init];
    }
    self.alert.delegate = self;
    [self.alert setTitle:self.info.title];
    [self.alert setMessage:self.info.desc];
    
    if ([self.info.enable boolValue]) {
        if ([self.info.uptype intValue] == kNeedForceUpdate) {
            [self.alert addButtonWithTitle:kUpdateButtonTitle];
            self.alert.cancelButtonIndex = -1;
            self.status = kNeedForceUpdate;
            self.completeBlock(kNeedForceUpdate, self.alert, nil);
        }
        else if ([self.info.uptype intValue] == kNeedUsualUpdate)
        {
            [self.alert addButtonWithTitle:kUpdateButtonTitle];
            [self.alert addButtonWithTitle:kCancelButtonTitle];
            self.alert.cancelButtonIndex = 0;
            self.status = kNeedUsualUpdate;
            self.completeBlock(kNeedUsualUpdate, self.alert, nil);
        }
        else
        {
            DLOG(@"up type is not 1 or 2");
            self.status = kNeedNotUpdate;
            self.completeBlock(kNeedNotUpdate, nil, nil);
            [self checkUpdateEnd];

        }
    }
    else
    {
        self.status = kNeedNotUpdate;
        self.completeBlock(kNeedNotUpdate, nil, nil);
        [self checkUpdateEnd];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
    if ([btnTitle isEqualToString:kUpdateButtonTitle]) {
        
//        NSString *urlStr = [NSString stringWithFormat:
//                         @"https://itunes.apple.com/us/app/hao-dai-wang-dai-kuan-10miao/id921438269?l=zh&ls=1&mt=8"];
        
        NSString *urlStr = self.info.updateURL;
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        if (self.status == kNeedForceUpdate) {
            [self checkUpdateEnd];
            exit(0);
        }
    }
    [self checkUpdateEnd];
}

-(void) checkUpdateEnd
{
    self.uploadInfo = nil;
    self.completeBlock = nil;
    self.info = nil;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self.alert dismissWithClickedButtonIndex:self.alert.cancelButtonIndex animated:NO];
}

@end
